import 'package:flutter/foundation.dart';
import 'package:fluwx/fluwx.dart';

/// Fluwx 日志工具类
class FluwxLogger {
  static bool _isInitialized = false;
  static final Fluwx fluwx = Fluwx();

  /// 初始化 Fluwx 日志监听
  static void init() {
    if (_isInitialized) return;

    debugPrint('🔧 初始化 Fluwx 日志监听器...');

    // 监听所有微信响应事件
    fluwx.addSubscriber((response) {
      try {
        _logWeChatResponse(response);
      } catch (error, stackTrace) {
        debugPrint('❌ Fluwx 响应监听器错误: $error');
        if (kDebugMode) {
          debugPrint('Stack trace: $stackTrace');
        }
      }
    });

    _isInitialized = true;
    debugPrint('✅ Fluwx 日志监听器初始化完成');
  }

  /// 记录微信响应日志
  static void _logWeChatResponse(WeChatResponse response) {
    debugPrint('');
    debugPrint('═══════════════════════════════════════');
    debugPrint('📨 微信SDK响应 [${DateTime.now().toString().substring(11, 19)}]');
    debugPrint('═══════════════════════════════════════');
    debugPrint('响应类型: ${response.runtimeType}');

    if (response is WeChatShareResponse) {
      _logShareResponse(response);
    } else if (response is WeChatAuthResponse) {
      _logAuthResponse(response);
    } else if (response is WeChatPaymentResponse) {
      _logPaymentResponse(response);
    } else {
      debugPrint('其他响应: $response');
    }

    debugPrint('═══════════════════════════════════════');
    debugPrint('');
  }

  /// 记录分享响应
  static void _logShareResponse(WeChatShareResponse response) {
    debugPrint('📤 分享响应详情:');
    debugPrint('   错误码: ${response.errCode}');
    debugPrint('   错误信息: ${response.errStr ?? "无"}');
    debugPrint('   响应类型: ${response.type}');

    // 解析错误码含义
    String meaning = _getShareErrorMeaning(response.errCode ?? -999);
    debugPrint('   错误含义: $meaning');

    // 根据错误码显示不同的图标和建议
    switch (response.errCode ?? -999) {
      case 0:
        debugPrint('   状态: ✅ 成功');
        break;
      case -2:
        debugPrint('   状态: ⚠️ 用户取消');
        debugPrint('   建议: 用户主动取消了分享操作');
        break;
      case -3:
        debugPrint('   状态: ❌ 发送失败');
        debugPrint('   建议: 检查网络连接或分享内容格式');
        break;
      case -4:
        debugPrint('   状态: ❌ 授权拒绝');
        debugPrint('   建议: 检查微信AppID配置或应用授权');
        break;
      case -5:
        debugPrint('   状态: ❌ 微信不支持');
        debugPrint('   建议: 检查微信版本或分享内容类型');
        break;
      default:
        debugPrint('   状态: ❓ 未知错误');
        debugPrint('   建议: 查看微信官方文档或联系技术支持');
    }
  }

  /// 记录授权响应
  static void _logAuthResponse(WeChatAuthResponse response) {
    debugPrint('🔐 授权响应详情:');
    debugPrint('   错误码: ${response.errCode}');
    debugPrint('   错误信息: ${response.errStr ?? "无"}');
    debugPrint('   授权码: ${response.code ?? "无"}');
    debugPrint('   状态: ${response.state ?? "无"}');
    debugPrint('   语言: ${response.lang ?? "无"}');
    debugPrint('   国家: ${response.country ?? "无"}');
  }

  /// 记录支付响应
  static void _logPaymentResponse(WeChatPaymentResponse response) {
    debugPrint('💰 支付响应详情:');
    debugPrint('   错误码: ${response.errCode}');
    debugPrint('   错误信息: ${response.errStr ?? "无"}');
    // returnKey 属性在当前版本中不存在，暂时注释
    // debugPrint('   返回键: ${response.returnKey ?? "无"}');
  }

  /// 获取分享错误码含义
  static String _getShareErrorMeaning(int errCode) {
    switch (errCode) {
      case 0:
        return '成功';
      case -1:
        return '普通错误类型';
      case -2:
        return '用户点击取消并返回';
      case -3:
        return '发送失败';
      case -4:
        return '授权失败';
      case -5:
        return '微信不支持';
      default:
        return '未知错误码';
    }
  }

  /// 手动记录调试信息
  static void logDebug(String message) {
    if (kDebugMode) {
      debugPrint('🔍 [Fluwx Debug] $message');
    }
  }

  /// 手动记录错误信息
  static void logError(String message, [dynamic error]) {
    debugPrint('❌ [Fluwx Error] $message');
    if (error != null) {
      debugPrint('   详情: $error');
    }
  }

  /// 手动记录成功信息
  static void logSuccess(String message) {
    debugPrint('✅ [Fluwx Success] $message');
  }

  /// 记录微信SDK状态
  static Future<void> logWeChatStatus() async {
    debugPrint('');
    debugPrint('📊 微信SDK状态检查:');
    debugPrint('─────────────────────────');

    try {
      bool isInstalled = await Fluwx().isWeChatInstalled;
      debugPrint('微信安装状态: ${isInstalled ? "✅ 已安装" : "❌ 未安装"}');

      // isWeChatSupportApi 在当前版本中可能不存在，暂时注释
      // bool isWeChatSupportApi = await fluwx.isWeChatSupportApi;
      // debugPrint('微信API支持: ${isWeChatSupportApi ? "✅ 支持" : "❌ 不支持"}');
      debugPrint('微信API支持: 检查功能暂时不可用');
    } catch (e) {
      debugPrint('❌ 状态检查失败: $e');
    }

    debugPrint('─────────────────────────');
    debugPrint('');
  }
}
